import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ResponseInterceptor } from '@/response.interceptor';
import { json } from 'express';
import { AuthGuard } from '@nestjs/passport';
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { UnauthorizedFilter } from './filters/unauthorized.filter';

@Injectable()
class GlobalJwtAuthGuard implements CanActivate {
  private readonly jwtAuthGuard = AuthGuard('jwt');

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const guardInstance = new (this.jwtAuthGuard)();
    return guardInstance.canActivate(context) as Promise<boolean>;
  }
}


async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  // app.useGlobalGuards(new GlobalJwtAuthGuard());
  // 注册全局异常过滤器
  app.useGlobalFilters(new UnauthorizedFilter());
  // 设置全局前缀为 /api
  app.setGlobalPrefix('api');
  // 注册全局拦截器
  app.useGlobalInterceptors(new ResponseInterceptor());
  app.enableCors({
    origin: ['http://localhost:8888', 'http://localhost:5173'], // 允许的源
    methods: 'GET,HEAD,PUT,PATCH,POST,DELETE', // 允许的 HTTP 方法
    allowedHeaders: 'Content-Type, Accept, Authorization', // 允许的请求头
    credentials: true,
  });
  app.use(json())
  await app.listen(3000);
}
bootstrap();